import { Card, Button, Table, Modal, Form, Input, Upload, message } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import React, { useEffect, useState } from 'react'
import trademarkApi, { TrademarkData, TrademarkListData } from '@api/product/trademark'
import { ColumnsType } from 'antd/lib/table';

import './index.less'

export default function Trademark() {

    const [dataSource, setDataSource] = useState<TrademarkListData>([])
    const [page, setPage] = useState(1)
    const [limit, setLimit] = useState(5)
    const [total, setTotal] = useState(100)
    const [isShowDialog, setIsShowDialog] = useState(false)
    const [form] = Form.useForm()

    // 标签上 rowKey 代替这里的 key ?
    const columns: ColumnsType<TrademarkData> = [
        {
            title: '序号',
            // 对应数据中的字段
            render: (row, records, index) => index + 1,
            width: 80,
            align: 'center'
        },
        {
            title: '品牌名称',
            dataIndex: 'tmName',
        },
        {
            title: '品牌LOGO',
            render: row => <img className='logoImg' src={row.logoUrl} alt="" />
            // 要么写上 dataIndex: 'logoUrl' 然后下面直接 src={row}
        },
        {
            title: '操作',
            render: row => {
                return (
                    <>
                        <Button size='small' style={{ backgroundColor: '#E6A23C', color: '#fff', marginRight: '10px' }}
                            icon={<EditOutlined />} onClick={() => {editTrademark(row)}} >修改</Button>
                        <Button size='small' style={{ backgroundColor: '#F56C6C', color: '#fff' }}
                            icon={<DeleteOutlined />} onClick={() => {deleteTrademark(row)}} >删除</Button>
                    </>
                )
            },
            width: 240
        },
    ]

    useEffect(() => {
        getTardemark(page, limit)
        
    }, [])


    async function getTardemark(page: number, limit: number) {
        setPage(page)
        try {
            const result = await trademarkApi.getTrademark(page, limit)
            setDataSource(result.records)
            setTotal(result.total)
        } catch (error) {
            message.error('获取品牌列表失败')
        }
    }

    // Modal 对话框弹窗的按钮回调
    const handleOk = async () => {
        // 统一验证
        form.validateFields()
            .then(value => {
                onFinish(value)
            })
            .catch(error => {

            })
    }

    const handleCancel = () => {
        setIsShowDialog(false)
    }

    // Form 表单验证成功的回调
    const onFinish = async (value: any) => {
        console.log(value)
        // rowId 存在为更新, 否则为新增
        const tardemarkParamas = {
            id: rowId,
            tmName: value.tmName,
            logoUrl: value.tmLogo[value.tmLogo.length - 1].response ? value.tmLogo[value.tmLogo.length - 1].response.data : imageUrl
        }
        if (rowId) {
            try {
                await trademarkApi.updateTrademark(tardemarkParamas)
                message.success('更新成功')
                getTardemark(dataSource.length > 0 ? page : 1, limit)
                setIsShowDialog(false)
            } catch (error) {
                message.error('更新失败')
            }
        } else {
            try {
                await trademarkApi.addTrademark(tardemarkParamas)
                message.success('添加成功')
                getTardemark(1, limit)
                setIsShowDialog(false)
            } catch (error) {
                message.error('添加数据失败')
            }
        }
    }


    // upload 上传logo
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>('');

    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };

    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 格式文件');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片最大不能超过 2MB');
        }
        return isJpgOrPng && isLt2M;
    };

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj as RcFile, url => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    const normFile = (e: any) => {
        // console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };


    // 新增弹出对话框
    const showDia = () => {
        // form.resetFields(['tmName', 'fileList'])
        // 新增清空 rowId
        setRowId('')
        form.resetFields()
        setImageUrl('')
        setIsShowDialog(true)
    }

    
    const [rowId, setRowId] = useState<string | number>('')
    // 修改
    const editTrademark = (row: TrademarkData) => {
        setRowId(row.id as number)
        let temp = { ...row }
        setImageUrl(temp.logoUrl)

        form.setFieldsValue({
            tmName: temp.tmName,
            // 默认的 fileList, 去官网查
            // Form.Item 通过 name/valuePropName 去验证
            // 空对象也可以
            tmLogo: [
                {
                    // uid: '',
                    // name: '',
                    // status: '',
                    // url: '',
                },
            ]
        })
        
        setIsShowDialog(true)
    }

    // const checkImageUrl = (rules: any, value: any, callback: any) => {
    //     if (imageUrl) Promise.resolve()
    //     else Promise.reject()
    // }


    // 删除
    const deleteTrademark = async (row: TrademarkData) => {
        try {
            await trademarkApi.deleteTrademark(row.id as number)
            message.success('删除成功')
            getTardemark(dataSource.length === 1 ? page - 1 : page, limit)
        } catch (error) {
            message.error('删除失败')
        }
    }



    return (
        <>
            <Card>
                <Button onClick={showDia} type='primary' icon={<PlusOutlined />}>添加</Button>
            </Card>

            <Card>
                <Table
                    dataSource={dataSource}
                    columns={columns}
                    bordered
                    rowKey='id'
                    rowClassName='tableItem'
                    pagination={{
                        current: page,
                        pageSize: limit,
                        total,
                        pageSizeOptions: [5, 10, 15, 20],
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: total => `共 ${total} 条`,
                        onChange: (current, pageSize) => {
                            getTardemark(current, pageSize)
                        },
                        position: ['bottomCenter']
                    }}
                ></Table>

            </Card>

            <Modal
                title='添加品牌'
                visible={isShowDialog}
                onOk={handleOk}
                onCancel={handleCancel}
            >

                <Form
                    form={form}
                    labelCol={{ span: 5, offset: 1 }}
                    wrapperCol={{ span: 16 }}
                    onFinish={onFinish}
                >
                    <Form.Item
                        label='品牌名称'
                        rules={[{ required: true }, { min: 2, max: 20, message: '品牌名称长度为2-20' }]}
                        name='tmName'
                        style={{height: '50px', maxHeight: '50px', marginBottom: '20px'}}
                    >
                        <Input></Input>
                    </Form.Item>

                    <Form.Item
                        label='品牌LOGO'
                        // rules={[{ validator: (rules, value, callback) => checkImageUrl(rules, value, callback) }]}
                        rules={[{required: true}]}
                        name='tmLogo'
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                    >
                        <Upload
                            // 不能要 name, 否则 response.data 返回的数据就是空的
                            // name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action='/app-dev/admin/product/upload'
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%', height: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 6 }}>
                        <p>上传的图片必须是jpg且不能大于2M</p>
                    </Form.Item>
                </Form>
                
            </Modal>

        </>
    )
}
